﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using FtpWorkerRole.FtpServer;

namespace FtpWorkerRole.FtpCommand
{
    class PortCommand : CommandBase
    {
        public PortCommand(FtpSocketHandler handler)
            : base(handler)
        {
            commandName = "PORT";
        }

        public override void execute(string value)
        {
            if (!handler.Login)
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(530, "Please Login!"));
                return;
            }
            var sdata = value.Split(',');
            if (sdata.Length < 6)
            {
                Utils.sendMessage(handler.getSocket(), formatMessage(550, "Error in setting up data connection."));
            }
            else
            {
                handler.dataChannelSocketPort = (int.Parse(sdata[4]) << 8) + int.Parse(sdata[5]);
                handler.dataChannelSocketAddress = string.Join(".", sdata, 0, 4);
                Utils.sendMessage(handler.getSocket(),formatMessage(200,commandName+" command succeeds. "+handler.dataChannelSocketAddress+ " "+handler.dataChannelSocketPort));
            }
        }
    }
}
